package com.software.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.software.bean.*;
import com.software.dto.ProductReleaseDto;
import com.software.dto.UpdateProductDto;
import com.software.mapper.CategoryMapper;
import com.software.mapper.CustomerInfoMapper;
import com.software.mapper.ProductImageMapper;
import com.software.mapper.ProductMapper;
import com.software.service.ProductService;
import com.software.utils.AssertUtil;
import com.software.vo.ProductDetailVo;
import com.software.vo.ProductVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.*;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author wyj
 * @since 2024-03-24
 */
@Service
public class ProductServiceImpl extends ServiceImpl<ProductMapper, ProductBean> implements ProductService {

    @Autowired
    private CustomerInfoMapper customerInfoMapper;

    @Autowired
    private CategoryMapper categoryMapper;

    @Autowired
    private ProductMapper productMapper;

    @Autowired
    private ProductImageMapper productImageMapper;


    /**
     * @description:前端发布二手物品
     * @author: wyj
     * @date: 2024/3/29 10:02
     * @param:
     * @return:返回Product表ID
     */
    @Override
    public Integer postProductRelease(ProductReleaseDto releaseDto) {
        // 参数校验
        AssertUtil.isTrue(releaseDto.getFile() == null, "file异常");
        AssertUtil.isTrue(releaseDto.getCategoryId() == null, "参数异常");
        AssertUtil.isTrue(releaseDto.getCustomerId() == null, "参数异常");
        AssertUtil.isTrue(StringUtils.isEmpty(releaseDto.getQuality()), "品质 参数异常");
        AssertUtil.isTrue(StringUtils.isEmpty(releaseDto.getDesc()), "描述参数异常");
        AssertUtil.isTrue(releaseDto.getPrice() == 0, "参数异常");
        // 判断参数是否合法
        CustomerInfoBean customerInfoBean = customerInfoMapper.selectById(releaseDto.getCustomerId());
        AssertUtil.isTrue(customerInfoBean == null, "参数不合法");
        CategoryBean categoryBean = categoryMapper.selectById(releaseDto.getCategoryId());
        AssertUtil.isTrue(categoryBean == null, "参数不合法");
        // 发布
        ProductBean productBean = new ProductBean();
        productBean.setProductCreateTime(new Date());
        productBean.setProductUpdateTime(new Date());
        productBean.setProductQuality(releaseDto.getQuality());
        productBean.setProductPrice(releaseDto.getPrice());
        productBean.setProductDesc(releaseDto.getDesc());
        productBean.setCategoryId(releaseDto.getCategoryId());
        productBean.setCustomerId(releaseDto.getCustomerId());
        productBean.setIsHome(0);
        //status 0 标识审核中
        productBean.setProductStatus(0);
        String s = saveImage(releaseDto.getFile());
        AssertUtil.isTrue(StringUtils.isEmpty(s), "URL异常");
        productBean.setProductCoverImage(s);

        int insert = productMapper.insert(productBean);
        AssertUtil.isTrue(insert != 1, "插入异常");
        return productBean.getId();
    }

    /**
     * @description:我的发布列表，无需返回是否为空，有可能没发布过东西
     * @author: wyj
     * @date: 2024/4/1 20:47
     * @param:
     * @return:
     */
    @Override
    public List<ProductBean> getReleaseListByCid(Integer customerId) {
        AssertUtil.isTrue(customerId == null, "参数异常");
        List<ProductBean> list = productMapper.selectReleaseList(customerId);
        return list;
    }

    /**
     * @description:后台审核列表
     * @author: wyj
     * @date: 2024/4/1 22:27
     * @param:status==0
     * @return:
     */
    @Override
    public List<ProductBean> getReleaseProductList() {
        List<ProductBean> releaseProductList = productMapper.getReleaseProductList();
        return releaseProductList;
    }

    /**
     * @description:批量审核
     * @author: wyj
     * @date: 2024/4/2 15:00
     * @param:
     * @return:
     */
    @Override
    public Integer auditBatch(Integer[] auditIds) {
        AssertUtil.isTrue(auditIds == null || auditIds.length == 0, "参数异常");
        List<Integer> list = new ArrayList<>();
        for (Integer auditId : auditIds) {
            list.add(auditId);
        }
        List<ProductBean> resultList = productMapper.selectBatchIds(list);
        for (ProductBean productBean : resultList) {
            productBean.setProductStatus(1);
        }

        boolean b = this.updateBatchById(resultList);
        AssertUtil.isTrue(b != true, "更新失败");
        return b == true ? 1 : 0;
    }

    /**
     * @description:分页展示列表
     * @author: wyj
     * @date: 2024/4/2 16:25
     * @param:展示所有展示中的发布订单
     * @return:
     */
    @Override
    public IPage<ProductBean> getAllProductDisplayList(Integer pageNum, Integer pageSize) {
        // 参数校验
        AssertUtil.isTrue(pageNum == null, "参数异常");
        AssertUtil.isTrue(pageSize == null, "参数异常");
        Page<ProductBean> page = new Page<>();
        page.setSize(pageSize);
        page.setCurrent(pageNum);
        IPage<ProductBean> iPage = productMapper.getAllProductDisplayList(page);
        AssertUtil.isTrue(iPage == null, "返回值异常");
        return iPage;
    }

    /**
     * @description:主页展示功能
     * @author: wyj
     * @date: 2024/4/2 17:59
     * @param:
     * @return:
     */
    @Override
    public Integer updateProductHomeDisplay(Integer productId, Integer isHome) {
        // 参数校验
        AssertUtil.isTrue(productId == null, "参数异常");
        AssertUtil.isTrue(isHome == null, "参数异常");
        //判断productId 是否合法
        ProductBean productBean = productMapper.selectById(productId);
        AssertUtil.isTrue(productBean == null, "返回值异常");
        productBean.setIsHome(isHome);
        int i = productMapper.updateById(productBean);
        return i == 1 ? 1 : 0;
    }

    /**
     * @description:获取所有显示到主页上的商品
     * @author: wyj
     * @date: 2024/4/2 20:36
     * @param:isHome==1
     * @return:
     */
    @Override
    public IPage<ProductBean> getAllDisplayProduct(Integer pageSize, Integer pageNum) {
        Page<ProductBean> page = new Page<>();
        page.setSize(pageSize);
        page.setCurrent(pageNum);
        IPage<ProductBean> list = productMapper.getAllDisplayProduct(page);
        return list;
    }

    /**
     * @description:闲置物品详情
     * @author: wyj
     * @date: 2024/4/2 23:12
     * @param:
     * @return:返回详情+所有图片
     */
    @Override
    public ProductDetailVo getProductDetailByProductId(Integer productId) {
        AssertUtil.isTrue(productId == null, "参数异常");
        ProductBean productBean = productMapper.getProductDetailByProductId(productId);
        AssertUtil.isTrue(productBean == null, "返回值异常");
        List<ProductImageBean> imageBeanList = productImageMapper.getProductDetailImageListByProductId(productId);
        List<String> list = new LinkedList<>();
        list.add(productBean.getProductCoverImage());
        for (ProductImageBean productImageBean : imageBeanList) {
            list.add(productImageBean.getProductDetailImage());
        }

        ProductDetailVo productDetailVo = new ProductDetailVo();
        productDetailVo.setId(productBean.getId());
        productDetailVo.setList(list);
        productDetailVo.setProductDesc(productBean.getProductDesc());
        productDetailVo.setProductPrice(productBean.getProductPrice());
        productDetailVo.setProductStatus(productBean.getProductStatus());
        productDetailVo.setProductQuality(productBean.getProductQuality());
        productDetailVo.setProductCreateTime(productBean.getProductCreateTime());
        productDetailVo.setCustomerInfoBean(productBean.getCustomerInfoBean());
        productDetailVo.setCategoryBean(productBean.getCategoryBean());
        return productDetailVo;
    }

    /**
     * @description:点击主页中按钮进入商品详情页，返回商品详情信息+所有图片信息+发布者信息+分类信息+评论信息+评论者信息+评论时间+评论内容+评论图片信息
     * @author: wyj
     * @date: 2024/4/3 15:26
     * @param:
     * @return:根据分类查询商品列表
     */
    @Override
    public List<ProductBean> getProductListByCategoryId(Integer categoryId) {
        //参数校验
        AssertUtil.isTrue(categoryId == null || categoryId == 0, "参数异常");
        List<ProductBean> list = productMapper.getProductListByCategoryId(categoryId);
        return list;
    }

    /**
     * @description:搜索功能实现
     * @author: wyj
     * @date: 2024/4/5 17:10
     * @param:
     * @return:
     */
    @Override
    public List<ProductBean> getSearchByContent(String content) {
        AssertUtil.isTrue(StringUtils.isEmpty(content), "搜索内容为空");
        List<ProductBean> list = productMapper.getSearchByContent(content);
        return list;
    }

    /**
     * @description:查每个分类下的商品数量___近七天的用户发布数量
     * @author: wyj
     * @date: 2024/4/6 15:35
     * @param:
     * @return:
     */
    @Override
    public List<Map<String, Object>> getSevenDaysReleaseCountGroupByCategory() {
        List<Map<String, Object>> list = productMapper.getSevenDaysReleaseCountGroupByCategory();
        return list;
    }

    /**
     * @description:撤销审核
     * @author: wyj
     * @date: 2024/4/9 16:30
     * @param:
     * @return:
     */
    @Override
    public Integer removeAudit(Integer productId) {
        //参数校验
        AssertUtil.isTrue(productId == null, "参数异常");
        // 判断是否合法
        ProductBean productBean = productMapper.selectById(productId);
        AssertUtil.isTrue(productBean == null, "返回值异常");
        productBean.setProductStatus(0);
        // 主页不显示
        productBean.setIsHome(0);
        int i = productMapper.updateById(productBean);
        return i == 1 ? 1 : 0;
    }

    /**
     * @description:下架产品并删除图片
     * @author: wyj
     * @date: 2024/4/11 19:29
     * @param:
     * @return:
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Integer deleteProductById(Integer productId) {
        AssertUtil.isTrue(productId == null, "参数异常");
        ProductBean productBean = productMapper.selectById(productId);
        AssertUtil.isTrue(productBean == null, "产品信息异常");
        List<ProductImageBean> imgList = productImageMapper.selectImagesByProductId(productId);
        for (ProductImageBean productImageBean : imgList) {
            String url = productImageBean.getProductDetailImage();
            //删除图片
            Boolean delImageResult = deleteImage(url);
            AssertUtil.isTrue(delImageResult == false, "删除图片失败");
            int i = productImageMapper.deleteById(productImageBean.getId());
            AssertUtil.isTrue(i != 1, "删除图片失败2");
        }
        int i = productMapper.deleteById(productId);

        return i == 1 ? 1 : 0;
    }

    /**
     * @description:拒绝通过审核
     * @author: wyj
     * @date: 2024/4/13 13:57
     * @param:
     * @return:
     */
    @Override
    public Integer auditRejected(Integer id) {
        AssertUtil.isTrue(id == null, "参数异常");
        ProductBean productBean = productMapper.selectById(id);
        AssertUtil.isTrue(productBean == null, "产品信息异常");
        productBean.setProductStatus(5);
        int i = productMapper.updateById(productBean);
        return i == 1 ? 1 : 0;
    }

    /**
     * @description:获取商品信息用于编辑
     * @author: wyj
     * @date: 2024/4/13 14:25
     * @param:
     * @return:
     */
    @Override
    public ProductVo getProductInfoByIdForEdit(Integer pid) {
        AssertUtil.isTrue(pid == null, "参数异常");
        ProductBean productBean = productMapper.selectById(pid);
        AssertUtil.isTrue(productBean == null, "产品信息异常");
        List<ProductImageBean> productDetailImageListByProductId = productImageMapper.getProductDetailImageListByProductId(pid);

        List<String> imgList = new ArrayList<>();
        imgList.add(productBean.getProductCoverImage());
        for (ProductImageBean productImageBean : productDetailImageListByProductId) {
            imgList.add(productImageBean.getProductDetailImage());
        }
        ProductVo productVo = new ProductVo();
        productVo.setProductCategory(productBean.getCategoryId());
        productVo.setProductQuality(productBean.getProductQuality());
        productVo.setProductDesc(productBean.getProductDesc());
        productVo.setProductPrice(productBean.getProductPrice());
        productVo.setProductId(productBean.getId());
        productVo.setImgList(imgList);
        return productVo;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Integer updateProduct(UpdateProductDto updateProductDto) {
        AssertUtil.isTrue(updateProductDto.getFile() == null, "file异常");
        AssertUtil.isTrue(updateProductDto.getCategoryId() == null, "参数异常");
        AssertUtil.isTrue(updateProductDto.getProductId() == null, "参数异常");
        AssertUtil.isTrue(StringUtils.isEmpty(updateProductDto.getQuality()), "品质 参数异常");
        AssertUtil.isTrue(StringUtils.isEmpty(updateProductDto.getDesc()), "描述参数异常");
        AssertUtil.isTrue(updateProductDto.getPrice() == 0, "参数异常");
        ProductBean productBean = productMapper.selectById(updateProductDto.getProductId());
        AssertUtil.isTrue(productBean == null, "产品信息异常");

        // 删除原本的封面信息
        String coverImageURL  = productBean.getProductCoverImage();
        Boolean delCoverImage = deleteImage(coverImageURL);
        AssertUtil.isTrue(delCoverImage == false, "删除图片失败");
        // 保存新的封面信息
        productBean.setProductCoverImage(saveImage(updateProductDto.getFile()));
        productBean.setCategoryId(updateProductDto.getCategoryId());
        productBean.setProductQuality(updateProductDto.getQuality());
        productBean.setProductDesc(updateProductDto.getDesc());
        productBean.setProductPrice(updateProductDto.getPrice());
        productBean.setProductStatus(0);
        productBean.setIsHome(0);
        //删除原有图片
        List<ProductImageBean> imgList = productImageMapper.selectImagesByProductId(updateProductDto.getProductId());
        for (ProductImageBean productImageBean : imgList) {
            String url = productImageBean.getProductDetailImage();
            //删除图片
            Boolean delImageResult = deleteImage(url);
            AssertUtil.isTrue(delImageResult == false, "删除图片失败");
            int i = productImageMapper.deleteById(productImageBean.getId());
            AssertUtil.isTrue(i != 1, "删除图片失败2");
        }
        //更新productBean
        int i = productMapper.updateById(productBean);
        AssertUtil.isTrue(i != 1, "更新产品信息失败");
        return productBean.getId();
    }


    private String saveImage(MultipartFile file) {
        String realPath = "E:/img";
        String fileName = UUID.randomUUID().toString().replace("-", "");
        // 整个URL   最后拼接file的后缀名
        String imgURL = "http://localhost:8082/file/" + fileName + file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
        String filePath = realPath + "/" + fileName + file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
        try {
            file.transferTo(new File(filePath));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return imgURL;
    }

    // 删除图片
    private Boolean deleteImage(String url) {
        String imageUrl = url;
        //        String str= url.substring(url.lastIndexOf("/")+1);
        String endUrl = imageUrl.substring(imageUrl.lastIndexOf("/") + 1);
        String realPath = "E:/img";
        String filePath = realPath + "/" + endUrl;
        File file = new File(filePath);
        if (file.exists()) {
            file.delete();
        } else {
            return false;
        }
        return true;
    }

}
